6

vue router的使用

1、安装:npm install vue-router --save
2、新建router文件夹,建立index.js文件如下:

import Vue from 'vue'
import Router from 'vue-router'
//路由懒加载
const login = resolve => require(['../login.vue'], resolve);
const Apps = resolve => require(['../App.vue'], resolve);
const HelloWorld = resolve => require(['../components/HelloWorld'], resolve);
const second = resolve => require(['../components/second'], resolve);
const detail = resolve => require(['../components/detail'], resolve);

Vue.use(Router)

const routes = [
  {
    path: "/login",
    name: "login",
    component: login
  },
  {
    path: "/Apps",
    name: "Apps",
    component: Apps,
    children: [
      {
        path: "/HelloWorld",
        name: "HelloWorld",
        component: HelloWorld
      },
      {
        path: "/second",
        name: "second",
        component: second
      },
      {
        path: "/detail",
        name: "detail",
        component: detail
      }
    ]
  },
  {
    path: '/',
    redirect: '/login'
  }
]

var router = new Router({
  linkActiveClass:'list-active', //设置当前路由style
  routes
})
export default router;

3、在main.js中应用

import Vue from 'vue';
import router from './router';
var v = new Vue({
  el: '#app',
  router,
  components: {App},
  template: '<App/>',
  created: function () {

  }
})

4、在APP.vue中设置路由跳转

<template>
  <div id="apps">
    <div class="leftNav">
      <router-link to="/HelloWorld">链接一</router-link>
      <router-link to="/second">链接二</router-link>
    </div>
    <div class="rightCon">
      <router-view/>
    </div>
  </div>
</template>

<script>
  import HelloWorld from './components/HelloWorld'
  import second from './components/second'

  export default {
    name: 'Apps',
    components: {
      HelloWorld,
      second
    },
    data () {
      return {

      }
    }
  }
</script>

5、js跳转:this.$router.push({name: 'detail', query: {userInfo: thisName}})
6、vue-router默认是hash模式,切换成history模式

var router = new Router({
  mode: 'history',
  linkActiveClass:'list-active', //设置当前路由style
  routes
})

7、github:vue-router,欢迎star。


Rossy1
2.1k 声望2.5k 粉丝

做大娱乐家!